package com.morn.fanfou;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;

import com.morn.fanfou.model.User;
import com.morn.fanfou.widget.UserListAdapter;

public class SearchUserActivity extends Activity{
	private EditText nameText;
	private List<User> userList;
	private UserListAdapter userListAdapter;
	private ListView userListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_user);
		userList = getUserList("");
		findView();

	}

	private void findView() {
		userListView = (ListView) findViewById(R.id.searchUserListView);
		userListView.setCacheColorHint(Color.WHITE);
		userListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = getIntent();
				intent.putExtra("name", userList.get(arg2).getName());
				SearchUserActivity.this.setResult(Activity.RESULT_OK, intent);
				SearchUserActivity.this.finish();
				// Toast.makeText(SearchUserActivity.this,
				// userList.get(arg2).getName(), Toast.LENGTH_SHORT).show();
			}
		});
		nameText = (EditText) findViewById(R.id.searchUserEditText);
		nameText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				List<User> temp = getUserList(s.toString());
				userList.clear();
				userList.addAll(temp);
				userListAdapter.notifyDataSetChanged();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		userListAdapter = new UserListAdapter(this, userList);
		userListView.setAdapter(userListAdapter);

	}

	public List<User> getUserList(String name) {
		List<User> userList = null;
//		try {
//			userDao = getHelper().getUserDao();
//			String value = "%" + name + "%";
//			PreparedQuery<User> userWhere = userDao.queryBuilder()
//					.orderBy("spellName", true).limit(50).where()
//					.like("spellName", value).or()
//					.like("firstSpellName", value).or().like("name", value)
//					.prepare();
//			userList = userDao.query(userWhere);
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

		return userList;
	}

}
